/**
 * 角色相关API接口
 */
import { request } from '@/utils/request'
import type { ApiResponse } from '@/types/api'
import type { AxiosResponse } from 'axios'

// 角色信息接口
export interface Role {
  id: string
  name: string
  code: string
  description?: string
  permissions: string[]
  is_system: boolean
  is_active: boolean
  scope?: 'system' | 'project' // 角色作用域
  created_at?: string
  updated_at?: string
}

// 角色列表响应
export type RolesResponse = ApiResponse<Role[]>

// 简化的角色选项接口（用于注册页面）
export interface RoleOption {
  label: string
  value: string
  description?: string
}

// 角色选项缓存
let roleOptionsCache: RoleOption[] | null = null
let cacheTimestamp: number = 0
const CACHE_DURATION = 5 * 60 * 1000 // 5分钟缓存
const ROLE_RESOURCE = '/roles'

function ensureSuccess<T>(response: AxiosResponse<ApiResponse<T>>, defaultValue: T): T {
  const payload = response.data
  if (payload?.success && payload.data !== undefined) {
    return payload.data
  }
  return defaultValue
}

/**
 * 获取所有角色列表
 * @param scope 角色作用域筛选：'system' | 'project' | undefined（全部）
 */
export const getRoles = async (scope?: 'system' | 'project'): Promise<Role[]> => {
  try {
    const params: any = {
      showError: false, // 不显示错误消息，由调用方处理
      showLoading: false
    }
    if (scope) {
      params.params = { scope }
    }
    const response = await request.get<ApiResponse<Role[]>>(ROLE_RESOURCE, params as any)
    return ensureSuccess(response, [])
  } catch (error) {
    // 如果请求失败（包括权限错误），直接抛出，由调用方处理
    throw error
  }
}

/**
 * 获取角色选项列表（用于注册页面）
 * 使用公开API端点，无需认证，带缓存机制
 */
export const getRoleOptions = async (): Promise<RoleOption[]> => {
  // 检查缓存是否有效
  const now = Date.now()
  if (roleOptionsCache && (now - cacheTimestamp) < CACHE_DURATION) {
    return roleOptionsCache
  }

  try {
    const response = await request.get<ApiResponse<RoleOption[]>>(`${ROLE_RESOURCE}/options`)
    const options = ensureSuccess(response, [])
    roleOptionsCache = options
    cacheTimestamp = now
    return options
  } catch (error) {
    console.error('获取角色选项失败:', error)
    return roleOptionsCache ?? []
  }
}

/**
 * 获取用户可选择的角色列表（排除管理员角色）
 * 使用公开API端点，无需认证
 */
export const getSelectableRoles = async (): Promise<RoleOption[]> => {
  try {
    // 直接使用公开的角色选项API，该API已经排除了管理员角色
    return await getRoleOptions()
  } catch (error) {
    console.error('获取可选角色失败:', error)
    return []
  }
}

/**
 * 获取角色详情
 */
export const getRole = (id: string): Promise<Role> => {
  return request.get<ApiResponse<Role>>(`${ROLE_RESOURCE}/${id}`).then(response => {
    const payload = response.data
    if (payload?.success && payload.data) {
      return payload.data
    }
    throw new Error(payload?.message || '获取角色详情失败')
  })
}

/**
 * 创建角色
 */
export const createRole = (role: Partial<Role>): Promise<Role> => {
  return request.post<ApiResponse<Role>>(ROLE_RESOURCE, role).then(response => {
    const payload = response.data
    if (payload?.success && payload.data) {
      return payload.data
    }
    throw new Error(payload?.message || '创建角色失败')
  })
}

/**
 * 更新角色
 */
export const updateRole = (id: string, role: Partial<Role>): Promise<Role> => {
  return request.put<ApiResponse<Role>>(`${ROLE_RESOURCE}/${id}`, role).then(response => {
    const payload = response.data
    if (payload?.success && payload.data) {
      return payload.data
    }
    throw new Error(payload?.message || '更新角色失败')
  })
}

/**
 * 删除角色
 */
export const deleteRole = (id: string): Promise<void> => {
  return request.delete<ApiResponse<void>>(`${ROLE_RESOURCE}/${id}`).then(response => {
    if (!response.data?.success) {
      throw new Error(response.data?.message || '删除角色失败')
    }
  })
}

/**
 * 初始化系统角色
 */
export const initSystemRoles = (): Promise<{ created_count: number; updated_count: number }> => {
  return request.post<ApiResponse<{ created_count: number; updated_count: number }>>(`${ROLE_RESOURCE}/init`).then(response => {
    const payload = response.data
    if (payload?.success && payload.data) {
      return payload.data
    }
    throw new Error(payload?.message || '初始化系统角色失败')
  })
}

/**
 * 同步系统角色权限
 */
export const syncSystemRolePermissions = (): Promise<{ synced_count: number; failed_count: number; total_count: number }> => {
  return request.post<ApiResponse<{ synced_count: number; failed_count: number; total_count: number }>>(`${ROLE_RESOURCE}/sync-permissions`).then(response => {
    const payload = response.data
    if (payload?.success && payload.data) {
      return payload.data
    }
    throw new Error(payload?.message || '同步系统角色权限失败')
  })
}

/**
 * 获取系统角色列表
 */
export const getSystemRoles = (): Promise<Role[]> => {
  return request.get<ApiResponse<Role[]>>(`${ROLE_RESOURCE}/system`).then(response => {
    return ensureSuccess(response, [])
  })
}

/**
 * 获取自定义角色列表
 */
export const getCustomRoles = (): Promise<Role[]> => {
  return request.get<ApiResponse<Role[]>>(`${ROLE_RESOURCE}/custom`).then(response => {
    return ensureSuccess(response, [])
  })
}